import asyncio
from aiogram import Bot, Dispatcher, types, F
from aiogram.fsm.context import FSMContext
from aiogram.types import FSInputFile
import httpx
from icecream import ic
import aiofiles
import re
import zipfile
from bs4 import BeautifulSoup as bs
import os
import imgkit


semaphore = asyncio.Semaphore(5)


async def detect_re_number(text: str) -> list[str]:
    return re.findall(r'\b[A-Za-z]{4}\s?\d{7}\b', text)


async def pdf_du(filename: str, response: bytes) -> None:
    async with aiofiles.open(filename, 'wb') as f:
        await f.write(response)


class AsyncGetInfo:
    
    def __init__(self, cont_numb, mode='pdf') -> None:
        self.client = httpx.AsyncClient()
        self.cookies = {
            'PHPSESSID': '7230f75ad75928ad5ddeb23f1a855b0a',
            'ChatBox': 'false',
        }

        self.headers = {
            'accept': '*/*',
            'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            # 'cookie': 'PHPSESSID=7230f75ad75928ad5ddeb23f1a855b0a; ChatBox=false',
            'dnt': '1',
            'origin': 'https://cab.seafishport.ru',
            'referer': 'https://cab.seafishport.ru/',
            'sec-ch-ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
        }
        
        self.data = {
            'contnum': cont_numb,
        }
        if mode:
            self.data['mode'] = mode
        self.result = None
        
    async def post(self):
  
        response = await self.client.post(
            'https://cab.seafishport.ru/php_ajax/ajax_GetDetailedContInfo.php',
            # cookies=cookies,
            headers=self.headers,
            data=self.data,
        )
        self.result = response.text
        return response
    
    async def get_cont_inf(self, result):

        response = await self.client.get('https://cab.seafishport.ru/' + result)
        return response.content

async def folder_clear(directory: str) -> None:
    for file in os.listdir(directory):
        os.remove(os.path.join(directory, file))
    os.rmdir(directory)


async def create_zip(directory: str, filename: str) -> None:
    with zipfile.ZipFile(filename, 'w') as zip_file:
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith('.pdf'):
                    ic(file)
                    zip_file.write(os.path.join(root, file))


async def script_run(cont_list: list[str], message: types.Message, state: FSMContext) -> dict[str, bytes]:
    async with semaphore:
        task = []
        
        for i in cont_list:
            data = AsyncGetInfo(i)
            await message.answer(f'Отправка документа на контейнер\n{i}')
            await message.bot.send_chat_action(message.chat.id, 'typing')
            response = await data.post()
            result = response.text
            new_data = asyncio.create_task(data.get_cont_inf(result)) #await data.get_cont_inf()
            dir_name = f'{message.from_user.id}do1/'
            if not os.path.exists(dir_name):
                os.makedirs(dir_name)
            f_path = dir_name + i + '.pdf'
            asyncio.create_task(pdf_du(f_path, await new_data))
            f_paths = 'https://cab.seafishport.ru/' + result
            await message.bot.send_document(message.from_user.id, f_paths)
            # os.remove(f_path)
            await asyncio.sleep(0.2)
        await create_zip(dir_name, dir_name + 'pdf.zip')
        ic('Прошел архивацию')
        arch = FSInputFile(dir_name + 'pdf.zip')
        await message.answer('Формируем архив')
        await message.bot.send_chat_action(message.chat.id, 'typing')
        await message.answer_document(arch)
        task2 = asyncio.create_task(folder_clear(dir_name))


async def cont_infos(cont_num: str, message: types.Message=None, state: FSMContext=None) -> dict[str, bytes]:
    async with semaphore:
        task = []
        # mode='undefined'
        data = AsyncGetInfo(cont_num, mode='info')
        
        response = await data.post()
        result = response.text

        soup = bs(result, 'html.parser')

        rows = soup.find_all('tr')
        headers = [header.get_text(strip=True) for header in soup.find_all('th')]

        formatted_text = []
        # Перебираем строки таблицы и добавляем заголовок перед каждой
        for i, row in enumerate(rows):
            cells = row.find_all('td')
            row_text = ' | '.join(cell.get_text(strip=True) for cell in cells)
            if i < len(headers):
                # Добавляем заголовок секции
                formatted_text.append(f"<b>{headers[i]}</b>\n{row_text}")
            else:
                # Если заголовков меньше, чем строк, просто добавляем текст
                formatted_text.append(row_text)

        # Соединяем все строки в одну строку с разделителями новой строки
        result_text = '\n\n'.join(formatted_text)

        # Добавление жирного текста для важных уведомлений
        important_notice = soup.find('center').get_text(strip=True)
        result_text += f"\n\n<b>{important_notice}</b>"
        result_text = result_text.replace("'", '')
        ic(result)
        
        return 'Сведения о контейнере: ' + result_text

        
        
async def main():
    await cont_infos('RRSU8164022')

if __name__ == '__main__':
    asyncio.run(main())